<template>
  <div class="login-container">
    <a-card class="login-card" title="登录">
      <a-form
        :model="formState"
        name="login"
        @finish="handleFinish"
        @finishFailed="handleFinishFailed"
      >
        <a-form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名!' }]"
        >
          <a-input v-model:value="formState.username">
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: true, message: '请输入密码!' }]"
        >
          <a-input-password v-model:value="formState.password">
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item>
          <a-checkbox v-model:checked="formState.remember_me">
            记住我
          </a-checkbox>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loading" block>
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import { defineComponent, reactive, ref } from 'vue';
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import SparkMD5 from 'spark-md5';
import request from '../utils/request';

// 获取设备信息
function getDeviceInfo() {
  const userAgent = navigator.userAgent;
  return {
    type: 'browser',
    os: userAgent.includes('Windows') ? 'Windows' : 
        userAgent.includes('Mac') ? 'MacOS' : 
        userAgent.includes('Linux') ? 'Linux' : 'Unknown',
    client: `${navigator.userAgent.match(/Chrome\/([0-9.]+)/)?.[0] || 'Unknown Browser'}`
  };
}

// 生成设备ID
function generateDeviceId() {
  const storedDeviceId = localStorage.getItem('deviceId');
  if (storedDeviceId) return storedDeviceId;
  
  // 使用时间戳、随机数和用户代理生成唯一设备ID
  const seed = Date.now() + Math.random() + navigator.userAgent;
  const hash = SparkMD5.hash(seed);
  const newDeviceId = 'device-' + hash.substr(0, 16);
  localStorage.setItem('deviceId', newDeviceId);
  return newDeviceId;
}

export default defineComponent({
  name: 'Login',
  components: {
    UserOutlined,
    LockOutlined,
  },
  setup() {
    const loading = ref(false);
    const formState = reactive({
      username: '',
      password: '',
      remember_me: true
    });

    const handleFinish = async (values) => {
      try {
        loading.value = true;
        
        // 执行登录
        const deviceId = generateDeviceId();
        const response = await request.post('/v1/auth/login', {
          username: values.username,
          password: values.password,
          device_id: deviceId,
          device_info: getDeviceInfo(),
          remember_me: formState.remember_me
        });
        
        // 存储认证信息
        localStorage.setItem('access_token', response.data.access_token);
        localStorage.setItem('refresh_token', response.data.refresh_token);
        localStorage.setItem('token_expires', Date.now() + (response.data.expires_in * 1000));
        localStorage.setItem('user_info', JSON.stringify(response.data.user));
        
        message.success('登录成功');
        window.location.href = '/';
        
      } catch (error) {
        message.error(error.message || '登录失败');
      } finally {
        loading.value = false;
      }
    };

    const handleFinishFailed = (errorInfo) => {
      console.log('Failed:', errorInfo);
      message.error('请填写所有必填字段');
    };

    return {
      formState,
      loading,
      handleFinish,
      handleFinishFailed,
    };
  },
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-card {
  width: 100%;
  max-width: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

:deep(.ant-card-head-title) {
  text-align: center;
  font-size: 24px;
  padding: 12px 0;
}

:deep(.ant-form-item-label) {
  min-width: 70px;
  text-align: right;
}
</style>